package com.ning.cloud.common.exception;

import com.ning.cloud.common.enums.ErrorCode;
import com.ning.cloud.common.util.Response;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理类
 */
@Slf4j
@RestControllerAdvice
@AllArgsConstructor
public class GlobalExceptionHandler {

    /**
     * 通用业务异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = ServiceException.class)
    public Response handleServiceException(ServiceException e) {
        return Response.error(e.getCode(), e.getMessage());
    }

    /**
     * 参数校验处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Response handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getField() + fieldError.getDefaultMessage();
            }
        }
        return Response.error(message);
    }

    /**
     * 参数绑定异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    public Response handleValidException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getField()+fieldError.getDefaultMessage();
            }
        }
        return Response.error(message);
    }

    @ResponseBody
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Response jsonParseExceptionHandle(HttpMessageNotReadableException e) {
        log.error("解析错误:"+ e.getMessage());
        return Response.error("请求参数错误（json格式错误或类型错误等）");
    }

    /**
     * 不支持的请求方法
     *
     * @param request
     * @param response
     * @param e
     * @return
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Response methodNotSupportHandle(HttpServletRequest request, HttpServletResponse response, HttpRequestMethodNotSupportedException e) {
        log.error("请求方法不正确，请求路径: "+request.getRequestURL().toString(), e);
        return Response.error(ErrorCode.METHOD_NOT_ALLOWED);
    }


    /**
     * 兜底异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Response handleException(Exception e) {
        log.error("内部异常", e.getMessage(), e);
        return Response.error(ErrorCode.INTERNAL_ERROR);
    }
}
